<template>
	<MyPage title="开通会员" :isback="true">
		<view slot="gBody">
			<view class="my-title" style="margin-top:40rpx">会员类型</view>
			<scroll-view scroll-x="true" class="main-scroll">
				<view class="main-scroll-box">
					<view class="list" v-for="(item, index) in vipDataList" :key="index"
						:class="vipIndex==index?'cur':''" @click="getprice(index)">
						<view class="title">{{item.name}}</view>
						<view class="grey txt"><u-icon class="right" size="38" name="checkmark-circle-fill"
								:color="vipIndex==index?'#eeb115':'#ddd'"></u-icon>{{item.describe}}</view>
					</view>
				</view>
			</scroll-view>

			<view class="my-title">选择时长</view>
			<scroll-view scroll-x="true" class="main-scroll">
				<view class="main-scroll-box main-scroll-box2">
					<view class="list" v-for="(item, index) in priceList" :key="index"
						:class="priceIndex==index?'cur':''" @click="priceIndex=index">
						<view class="name">{{item.name}}</view>
						<view class="title">￥<text>{{item.price}}</text></view>
						<view class="grey txt">{{priceFilter(item)}}</view>
					</view>
				</view>
			</scroll-view>
			<template v-if="appleShow">
				<view class="my-title">支付方式</view>
				<view class="main">
					<view class="page-card">
						<u-cell-item title="微信" :arrow="false" @click="type=1">
							<u-icon slot="icon" size="65" name="weixin-circle-fill" color="#2ab047"
								style="margin-right:20rpx"></u-icon>
							<u-icon slot="right-icon" size="38" name="checkmark-circle-fill"
								:color="type==1?'#eeb115':'#ddd'"></u-icon>
						</u-cell-item>
						<u-cell-item title="支付宝" :arrow="false" @click="type=2">
							<u-icon slot="icon" size="65" name="zhifubao-circle-fill" color="#1362ff"
								style="margin-right:20rpx"></u-icon>
							<u-icon slot="right-icon" size="38" name="checkmark-circle-fill"
								:color="type==2?'#eeb115':'#ddd'"></u-icon>
						</u-cell-item>
						<u-cell-item :title="'余额支付（'+maxMoney+'元）'" :arrow="false" @click="type=3">
							<u-icon slot="icon" size="65" name="rmb-circle-fill" color="#eeb115"
								style="margin-right:20rpx"></u-icon>
							<u-icon slot="right-icon" size="38" name="checkmark-circle-fill"
								:color="type==3?'#eeb115':'#ddd'"></u-icon>
						</u-cell-item>
					</view>
				</view>
			</template>
			<view class="grey agreement">开通前请阅读<text class="grey"
					@click="$utils.navigateTo('/agreement/agreement',{id:49})">《会员服务协议》</text></view>

			<u-button type="warning" shape="circle" class="btn" @click="btnSubmit">￥<text
					class="money">{{priceList[priceIndex].price}}</text>立即支付</u-button>
		</view>
	</MyPage>
</template>

<script>
	let iapChannel = null,
		productId = 'card38',
		productIds = ['card88', 'card288', 'card38', 'card228', 'card468', 'card98', 'card168', 'card358', 'card68'];
	import uQRCode from '@/js_sdk/Sansnn-uQRCode/uqrcode.js'
	import mixin from "@/libs/mixin.js";
	import {
		getCardinfoData,
		sendPayClue,
		Gopay
	} from '@/api/index.js'
	import {
		getWalletInfo
	} from '@/api/wallet.js'
	export default {
		mixins: [mixin],
		data() {
			return {
				vipIndex: 0,
				vipDataList: [],
				priceIndex: 0,
				priceList: [{
						id: 1,
						name: '1个月',
						month: 1,
						price: 58
					},
					{
						id: 2,
						name: '3个月',
						month: 3,
						price: 148
					},
					{
						id: 3,
						name: '6个月',
						month: 6,
						price: 249
					},
					{
						id: 4,
						name: '12个月',
						month: 12,
						price: 419
					},
					{
						id: 5,
						name: '24个月',
						month: 24,
						price: 669
					}
				],
				type: 1,
				appleShow: true,
				maxMoney: "0.00"
			}
		},
		onLoad(option) {
			//检测当前平台，如果是苹果系统，隐藏其他支付
			uni.getSystemInfo({
				success: (res) => {
					if (res.platform == "ios" || res.platform == "mac") {
						this.appleShow = false;
						this.type = 4;
					}
				}
			});
			// 获取数据
			this.vipIndex = option.vipIndex ? option.vipIndex : 0;
			this.getCardinfoData(this.vipIndex);
			plus.payment.getChannels((channels) => {
				console.log("获取到channel" + JSON.stringify(channels))
				for (var i in channels) {
					var channel = channels[i];
					if (channel.id === 'appleiap') {
						iapChannel = channel;
						this.requestOrder();
					}
				}
				if (!iapChannel) {
					this.errorMsg()
				}
			}, (error) => {
				this.errorMsg()
			});
		},
		methods: {
			requestOrder() {
				uni.showLoading({
					title: '检测支付环境...'
				})
				iapChannel.requestOrder(productIds, (orderList) => { //必须调用此方法才能进行 iap 支付  
					this.disabled = false;
					console.log('requestOrder success666: ' + JSON.stringify(orderList));
					uni.hideLoading();
				}, (e) => {
					console.log('requestOrder failed: ' + JSON.stringify(e));
					uni.hideLoading();
					this.errorMsg()
				});
			},
			// filter-价格计算
			priceFilter(item) {
				let price = item.price,
					endPrice = (price / item.month).toFixed(1);
				if (price == endPrice) {
					return '限时特惠';
				} else {
					return '仅￥' + endPrice + '/月';
				};
			},
			// 获取数据
			getCardinfoData(id) {
				getCardinfoData({
					id: id
				}).then(res => {
					this.vipDataList = res.list.vipDataList;
					this.priceList = res.list.priceList;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				});
				//获取钱包金额数据
				getWalletInfo({
					token: this.$store.state.app.token
				}).then(res => {
					this.maxMoney = res.money;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				});
			},
			getprice(index) {
				this.vipIndex = index;
				getCardinfoData({
					id: index
				}).then(res => {
					this.vipDataList = res.list.vipDataList;
					this.priceList = res.list.priceList;
				}).catch(err => {
					uni.showToast({
						title: err.msg,
						icon: 'none'
					})
				});
			},
			// #ifndef H5


			// pay(ordersn) {
			//   let selectedProvider = ''
			//     if(this.type==2){
			// 		selectedProvider = 'alipay';
			// 	}
			// 	if(this.type==1){
			// 		selectedProvider = 'wxpay';
			// 	}
			// 	console.log("8888: " + JSON.stringify(selectedProvider));
			// 	console.log("ordersn: " + JSON.stringify(ordersn));
			//     return uniCloud.callFunction({
			//       name: 'pay',
			//       data: {
			//         provider:selectedProvider,
			//         outTradeNo: ordersn,
			// 		lx:1
			//       }
			//     }).then((res) => {
			//     if (res.result.orderInfo) {
			//       return new Promise((resolve, reject) => {
			//         uni.requestPayment({
			//           // #ifdef APP-PLUS
			//           provider: selectedProvider,
			//           // #endif
			//           // #ifdef MP-WEIXIN
			//           ...res.result.orderInfo,
			//           // #endif
			//           // #ifdef APP-PLUS || MP-ALIPAY
			//           orderInfo: res.result.orderInfo,
			//           // #endif
			//           complete() {
			//             resolve(res.result.outTradeNo)
			//           }
			//         })
			//       })
			//     } else {
			//       throw new Error(res.result.msg)
			//     }
			//   }).then((outTradeNo) => {
			// 	  console.log("999999: " + JSON.stringify(111111));
			//     return uniCloud.callFunction({
			//       name: 'order-query',
			//       data: {
			//         outTradeNo,
			// 		lx:1
			//       }
			//     })
			//   }).then((res) => {
			//     if (res.result.orderPaid) {
			// 	  sendPayClue();
			//       this.$utils.redirectTo('/common/success',{
			//       	title:"支付成功！",
			//       	subTitle:"赶快体验会员特权吧！",
			//       	btnValue:"返回首页",
			//       	url:'/index/index'
			//       });
			//     } else {
			//       uni.showModal({
			//         content: '订单未支付',
			//         showCancel: false
			//       })
			//     }
			//   }).catch((err) => {
			// 	  console.log("err: " + JSON.stringify(err));
			//     uni.showModal({
			//       content: err.message || '支付失败',
			//       showCancel: false
			//     })
			//   })
			// },
			// #endif
			pay(ordersn) {
				var that = this;
				Gopay({
					token: this.$store.state.app.token,
					ordersn: ordersn,
					paytype: 'vip',
				}).then(res => {
					if (res.list.err == 0) {
						uni.showToast({
							title: res.list.msg,
							icon: 'error'
						})
						return
					}
					if (that.type == 1) {
						var provider = 'wxpay';
					} else {
						var provider = 'alipay';
					}
					uni.requestPayment({
						provider: provider,
						orderInfo: res.list.data,
						success: function(res) {
							that.$utils.redirectTo('/common/success', {
								title: "支付成功！",
								subTitle: "赶快体验会员特权吧！",
								btnValue: "返回首页",
								url: '/index/index'
							});
						},
						fail: function(err) {
							console.log('fail:' + JSON.stringify(err));
						}
					});


				}).catch(err => {
					console.log("err: " + JSON.stringify(err));
				});
			},
			applePay(productId, ordersn) {
				uni.requestPayment({
					provider: 'appleiap',
					orderInfo: {
						productid: productId
					},
					success: (e) => {
						// 支付成功
						uni.request({
							url: 'http://www.txzh.com.cn/api.php?app=Default&act=applepay',
							method: 'POST',
							data: {
								lx: 1,
								token: this.$store.state.app.token,
								productid: productId,
								str: JSON.stringify(e),
								ordersn: ordersn
							},
							header: {
								'Content-Type': 'application/x-www-form-urlencoded',
								'X-Requested-With': 'xmlhttprequest'
							},
							success: res => {
								uni.hideLoading()
								if (res.data.list.err == 1) {
									uni.showModal({
										content: res.data.list.msg,
										showCancel: false
									})
								} else {
									sendPayClue();
									this.$utils.redirectTo('/common/success', {
										title: "订阅成功！",
										subTitle: "赶快体验会员特权吧！",
										btnValue: "返回首页",
										url: '/index/index'
									});
								}
							},
							fail: () => {},
							complete: () => {
								uni.hideLoading();
							}
						});

					},
					fail: (e) => {
						uni.hideLoading();
					},
					complete: () => {
						console.log("payment结束")
					}
				})
			},
			// 提交
			btnSubmit() {
				var that = this;
				console.log("8888: " + JSON.stringify(8888));
				//如果没有登录  跳转
				if (!this.$store.state.app.token) {
					this.$utils.redirectTo('/pages/login/login', {
						title: "登录",
						subTitle: "请先登录",
						btnValue: "请先登录",
						url: '/login/login'
					});
				} else {
					console.log("999: " + JSON.stringify(9999));
					let money = this.priceList[this.priceIndex].price;
					uni.request({
						url: 'http://www.txzh.com.cn/api.php?app=Default&act=buycard',
						method: 'POST',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'X-Requested-With': 'xmlhttprequest'
						},
						data: {
							type: this.vipIndex,
							price: this.priceIndex,
							money: money,
							token: this.$store.state.app.token,
							paytype: this.type
						},
						success: res => {

							if (this.type == 3) {
								//余额支付
								if (money > this.maxMoney) {
									uni.showToast({
										title: '余额不足，请选择其他支付方式！',
										icon: 'none'
									});
									return false;
								};
								uni.request({
									url: 'http://www.txzh.com.cn/api.php?app=Default&act=paymoney',
									method: 'POST',
									header: {
										'Content-Type': 'application/x-www-form-urlencoded',
										'X-Requested-With': 'xmlhttprequest'
									},
									data: {
										ordersn: res.data.list.ordersn
									},
									success: res => {
										if (res.data.list.err == 1) {
											uni.showModal({
												content: res.data.list.msg,
												showCancel: false
											})
										} else {
											sendPayClue();
											this.$utils.redirectTo('/common/success', {
												title: "支付成功！",
												subTitle: "赶快体验会员特权吧！",
												btnValue: "返回首页",
												url: '/index/index'
											});
										}
									},
									fail: () => {},
									complete: () => {}
								});
							} else if (this.type == 4) {
								//苹果支付
								uni.showLoading({
									title: '支付中...',
									mask: true
								})
								this.applePay('card' + money, res.data.list.ordersn);
							} else {

								that.pay(res.data.list.ordersn)
							}
						},
						fail: () => {},
						complete: () => {}
					});
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f3f3f3;
	}
</style>
<style lang="scss" scoped>
	.my-title {
		margin: 20rpx 40rpx 0;
		font-size: 34rpx;
		line-height: 45rpx;

		.grey {
			font-size: 26rpx;
		}
	}

	.main-scroll {
		margin-top: 28rpx;

		.main-scroll-box {
			height: 160rpx;
			padding-left: 40rpx;
			white-space: nowrap;

			.list {
				width: 250rpx;
				display: inline-block;
				margin-right: 3%;
				padding: 20rpx 18rpx 20rpx 25rpx;
				background: #fff;
				border: 1px #ddd solid;
				border-radius: 20rpx;
				white-space: nowrap;
				overflow: hidden;

				.title {
					font-size: 32rpx;
					font-weight: bold;
				}

				.txt {
					font-size: 24rpx;
					line-height: 1.7em;
					margin-top: 6rpx;
				}

				&.cur {
					background: #fff9ee;
					border-color: #e9a81e;

					.title {
						color: #c78706;
					}
				}
			}
		}

		.main-scroll-box2 {
			height: 240rpx;
			text-align: center;

			.list {
				width: 190rpx;
				padding: 28rpx 0;

				.title {
					margin-top: 8rpx;
					line-height: 55rpx;

					text {
						font-size: 46rpx;
					}
				}
			}
		}
	}

	.main {
		margin: 25rpx 40rpx 0;

		.page-card {
			padding: 20rpx 40rpx;
			border-radius: 20rpx;
			background: #fff;

			/deep/ .u-cell {
				padding: 15rpx 0;

				.u-cell_title {
					font-size: 30rpx;
					color: #333;
				}

				&:last-child:after {
					border: none;
				}
			}
		}
	}

	.agreement {
		margin-top: 20rpx;
		text-align: center;
		font-size: 24rpx;
	}

	.btn {
		position: fixed;
		bottom: 40rpx;
		left: 40rpx;
		right: 40rpx;
		background: linear-gradient(to right, #eeb115, #c17306);
		color: #fff !important;
		border: none;

		.money {
			margin-right: 18rpx;
			font-size: 36rpx;
			font-weight: bold;
		}
	}
</style>